<template>
  <div class="container">
    <el-row>
      <el-col :span="24">
        <div v-if="currentQuestion && currentQuestion.id">
          <h1 v-html="`${currentQuestion.id}. ${removeOuterPTags(currentQuestion.stem)}`"></h1>
          <el-form ref="questionForm">
            <el-radio-group v-if="currentQuestion.type !== '多选题'" v-model="selectedAnswer">
              <el-radio v-for="(option, index) in currentQuestion.options" :label="getLabel(index)" :key="index">
                <span>{{ getLabel(index) }}.</span>
                <span v-html="removeOuterPTags(option)"></span>
              </el-radio>
            </el-radio-group>
            <el-checkbox-group v-else v-model="selectedAnswers">
              <el-checkbox v-for="(option, index) in currentQuestion.options" :label="getLabel(index)" :key="index">
                <span>{{ getLabel(index) }}.</span>
                <span v-html="removeOuterPTags(option)"></span>
              </el-checkbox>
            </el-checkbox-group>
            <br>
            <el-button type="primary" @click="submitAnswer">Submit</el-button>
            <el-button @click="goToNextQuestion">Next</el-button>
            <el-button @click="goToPrevQuestion">Prev</el-button>
          </el-form>

          <div v-if="result" class="result-card">
            <el-card :class="{'correct-card': result === 'Correct', 'incorrect-card': result !== 'Correct'}">
              <div class="result-content">
                <h3>Result: {{ result }}</h3>
                <p>Correct Answer: {{ correctAnswer }}</p>
              </div>
            </el-card>
          </div>
        </div>
        <div v-else>
          <p>No more wrong questions to practice.</p>
        </div>
		
		
		<!-- 触发弹出框的按钮 -->
		  <el-button type="text" @click="showQuestionsDialog = true">Show All Questions</el-button>
		
		  <!-- 选题的弹出框 -->
		  <el-dialog title="All Questions" :visible.sync="showQuestionsDialog">
		    <el-list>
		      <el-list-item class="popup-item" v-for="(question, index) in wrongQuestions" :key="question.id" @click="goToQuestion(index)">
		        {{ question.id }}
		      </el-list-item>
		    </el-list>
		  </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>


<script>
import axios from 'axios';

export default {
  data() {
    return {
      wrongQuestions: [], // 答错的题目列表
      currentQuestionIndex: 0, // 当前题目的索引
      selectedAnswer: '', // 用户选中的答案（单选题）
      selectedAnswers: [], // 用户选中的答案（多选题）
      result: '', // 答题结果
      correctAnswer: '', // 正确答案
	  showQuestionsDialog: false, // 控制对话框的显示
    };
  },
  computed: {
    currentQuestion() {
        // 确保 currentQuestionIndex 在范围内
        if (this.currentQuestionIndex >= 0 && this.currentQuestionIndex < this.wrongQuestions.length) {
          return this.wrongQuestions[this.currentQuestionIndex];
        }
        return null; // 如果超出范围，返回 null
      },
  },
  created() {
    this.loadWrongQuestions();
  },
  methods: {
	    goToQuestion(index) {
	      this.currentQuestionIndex = index;
	      this.resetAnswer();
	      this.showQuestionsDialog = false; // 关闭对话框
	    },
    loadWrongQuestions() {
      axios.get('https://www.seedstudio.cn:3001/practice/all') // 假设这个接口返回所有题目
        .then(response => {
          let allQuestions = response.data; // 所有题目的数组
          let completed = JSON.parse(localStorage.getItem('completedQuestions')) || {};
    
          this.wrongQuestions = allQuestions.filter(question => completed[question.id] === false);
    
          // 如果当前索引超出错题列表范围，重置索引
          if (this.currentQuestionIndex >= this.wrongQuestions.length) {
            this.currentQuestionIndex = 0;
          }
        })
        .catch(error => {
          console.error('Error loading questions:', error);
          // 错误处理...
        });
    },
    submitAnswer() {
      if (this.currentQuestion.type !== '多选题') {
        this.result = this.selectedAnswer === this.currentQuestion.correctAnswer ? 'Correct' : 'Incorrect';
      } else {
        // 对多选题的答案进行排序，以便比较
        let sortedUserAnswers = [...this.selectedAnswers].sort();
        let sortedCorrectAnswers = this.currentQuestion.correctAnswer.split('').sort();
        this.result = JSON.stringify(sortedUserAnswers) === JSON.stringify(sortedCorrectAnswers) ? 'Correct' : 'Incorrect';
      }

      this.correctAnswer = this.currentQuestion.correctAnswer;
    },
    goToNextQuestion() {
      if (this.currentQuestionIndex < this.wrongQuestions.length - 1) {
        this.currentQuestionIndex++;
        this.resetAnswer();
      }
    },
    goToPrevQuestion() {
      if (this.currentQuestionIndex > 0) {
        this.currentQuestionIndex--;
        this.resetAnswer();
      }
    },
    resetAnswer() {
      this.selectedAnswer = '';
      this.selectedAnswers = [];
      this.result = '';
      this.correctAnswer = '';
    },
    getLabel(index) {
      return ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'][index];
    },
    removeOuterPTags(text) {
      const regex = /^<p>(.*)<\/p>$/i;
      const match = regex.exec(text);
      return match ? match[1] : text;
    },
  },
};
</script>


<style scoped>
	
	.popup-item {
		padding: 2px;
		border: 1px solid #e5e5e5;
		border-radius: 4px;
		margin: 4px;
		display: inline-block;
		width: 25px;
		text-align: center;
		color: #999;
	}
  .container {
    max-width: 800px;
    margin: 20px auto;
    padding: 20px;
    background-color: #fff;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
  }

  h1 {
    font-size: 20px;
    margin-bottom: 15px;
    color: #333;
  }

  .el-form {
    margin-bottom: 20px;
  }

  .el-radio-group, .el-checkbox-group {
    margin: 10px 0;
  }

  .el-radio, .el-checkbox {
    margin: 5px 0;
    line-height: 1.6;
  }

  .el-radio__label, .el-checkbox__label {
    font-size: 16px;
    color: #666;
  }

  .el-button {
    margin-right: 10px;
  }

  .result-card {
    margin-top: 20px;
    padding: 10px;
    background-color: #f5f5f5;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .correct-card {
    border-left: 4px solid #67c23a;
  }

  .incorrect-card {
    border-left: 4px solid #f56c6c;
  }

  .result-content h3 {
    font-size: 18px;
    color: #333;
  }

  .result-content p {
    font-size: 16px;
    color: #666;
  }

  @media (max-width: 600px) {
    .container {
      margin: 10px;
      padding: 15px;
    }

    h1 {
      font-size: 18px;
    }

    .el-radio__label, .el-checkbox__label {
      font-size: 14px;
    }

    .result-content h3, .result-content p {
      font-size: 14px;
    }
  }
</style>
